<template>
  <div class="promotion-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>促销活动管理</h2>
      <p>管理各类促销活动，包括满减、折扣、买赠等营销活动</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon size="32" color="#409EFF"><Promotion /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ promotionStats.totalPromotions }}</div>
              <div class="stats-label">总活动数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon size="32" color="#67C23A"><CircleCheck /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ promotionStats.activePromotions }}</div>
              <div class="stats-label">进行中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon size="32" color="#E6A23C"><Money /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ promotionStats.totalSavings }}</div>
              <div class="stats-label">总优惠金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon size="32" color="#F56C6C"><TrendCharts /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ promotionStats.participationRate }}%</div>
              <div class="stats-label">参与率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.promotionName" placeholder="请输入活动名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="满减活动" value="full_reduction" />
            <el-option label="折扣活动" value="discount" />
            <el-option label="买赠活动" value="buy_gift" />
            <el-option label="秒杀活动" value="flash_sale" />
            <el-option label="团购活动" value="group_buy" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="待开始" value="pending" />
            <el-option label="进行中" value="active" />
            <el-option label="已结束" value="ended" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新建活动
        </el-button>
        <el-button type="success" @click="handleBatchStart">
          <el-icon><VideoPlay /></el-icon>
          批量启动
        </el-button>
        <el-button type="warning" @click="handleBatchPause">
          <el-icon><VideoPause /></el-icon>
          批量暂停
        </el-button>
        <el-button type="info" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="promotionNo" label="活动编号" width="140" fixed="left" />
        <el-table-column prop="promotionName" label="活动名称" width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="small">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="discountInfo" label="优惠信息" width="180">
          <template #default="{ row }">
            <div class="discount-info">
              <span class="discount-text">{{ formatDiscountInfo(row) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="160" />
        <el-table-column prop="endTime" label="结束时间" width="160" />
        <el-table-column prop="participantCount" label="参与人数" width="100">
          <template #default="{ row }">
            <span class="participant-count">{{ row.participantCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalSavings" label="优惠金额" width="120">
          <template #default="{ row }">
            <span class="savings-amount">¥{{ row.totalSavings.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(row)" v-if="row.status === 'pending'">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleDropdownCommand(command, row)">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="start" v-if="row.status === 'pending'">启动活动</el-dropdown-item>
                  <el-dropdown-item command="pause" v-if="row.status === 'active'">暂停活动</el-dropdown-item>
                  <el-dropdown-item command="resume" v-if="row.status === 'paused'">恢复活动</el-dropdown-item>
                  <el-dropdown-item command="end" v-if="['active', 'paused'].includes(row.status)">结束活动</el-dropdown-item>
                  <el-dropdown-item command="copy">复制活动</el-dropdown-item>
                  <el-dropdown-item command="delete" v-if="row.status === 'pending'">删除活动</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 活动详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="活动详情" width="70%" :before-close="handleDetailClose">
      <div v-if="currentPromotion" class="promotion-detail">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="活动编号">{{ currentPromotion.promotionNo }}</el-descriptions-item>
              <el-descriptions-item label="活动名称">{{ currentPromotion.promotionName }}</el-descriptions-item>
              <el-descriptions-item label="活动类型">
                <el-tag :type="getTypeTagType(currentPromotion.type)">
                  {{ getTypeText(currentPromotion.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="活动状态">
                <el-tag :type="getStatusTagType(currentPromotion.status)">
                  {{ getStatusText(currentPromotion.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="开始时间">{{ currentPromotion.startTime }}</el-descriptions-item>
              <el-descriptions-item label="结束时间">{{ currentPromotion.endTime }}</el-descriptions-item>
              <el-descriptions-item label="参与人数">{{ currentPromotion.participantCount }}</el-descriptions-item>
              <el-descriptions-item label="优惠金额">¥{{ currentPromotion.totalSavings.toFixed(2) }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ currentPromotion.createTime }}</el-descriptions-item>
              <el-descriptions-item label="创建人">{{ currentPromotion.creator }}</el-descriptions-item>
              <el-descriptions-item label="活动描述" :span="2">{{ currentPromotion.description }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="规则配置" name="rules">
            <div class="rules-config">
              <h4>优惠规则</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="优惠类型">{{ getTypeText(currentPromotion.type) }}</el-descriptions-item>
                <el-descriptions-item label="优惠条件">{{ currentPromotion.rules.condition }}</el-descriptions-item>
                <el-descriptions-item label="优惠内容">{{ currentPromotion.rules.benefit }}</el-descriptions-item>
                <el-descriptions-item label="使用限制">{{ currentPromotion.rules.limitation }}</el-descriptions-item>
              </el-descriptions>
              
              <h4 style="margin-top: 20px;">适用商品</h4>
              <el-table :data="currentPromotion.applicableProducts" border size="small">
                <el-table-column prop="productCode" label="商品编码" width="120" />
                <el-table-column prop="productName" label="商品名称" />
                <el-table-column prop="category" label="分类" width="120" />
                <el-table-column prop="price" label="原价" width="100">
                  <template #default="{ row }">
                    ¥{{ row.price.toFixed(2) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="参与记录" name="participants">
            <el-table :data="currentPromotion.participants" border>
              <el-table-column prop="memberNo" label="会员编号" width="120" />
              <el-table-column prop="memberName" label="会员姓名" width="120" />
              <el-table-column prop="orderNo" label="订单号" width="180" />
              <el-table-column prop="originalAmount" label="原金额" width="100">
                <template #default="{ row }">
                  ¥{{ row.originalAmount.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="discountAmount" label="优惠金额" width="100">
                <template #default="{ row }">
                  <span class="discount-amount">-¥{{ row.discountAmount.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="finalAmount" label="实付金额" width="100">
                <template #default="{ row }">
                  ¥{{ row.finalAmount.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="participateTime" label="参与时间" width="160" />
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="数据统计" name="statistics">
            <div class="statistics-content">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="chart-container">
                    <h4>参与趋势</h4>
                    <div ref="participationChart" style="height: 300px;"></div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="chart-container">
                    <h4>优惠分布</h4>
                    <div ref="discountChart" style="height: 300px;"></div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 新增/编辑活动对话框 -->
    <el-dialog v-model="formDialogVisible" :title="isEdit ? '编辑活动' : '新建活动'" width="60%">
      <el-form :model="promotionForm" :rules="promotionRules" ref="promotionFormRef" label-width="120px">
        <el-tabs v-model="formActiveTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="活动名称" prop="promotionName">
                  <el-input v-model="promotionForm.promotionName" placeholder="请输入活动名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动类型" prop="type">
                  <el-select v-model="promotionForm.type" placeholder="请选择活动类型" style="width: 100%">
                    <el-option label="满减活动" value="full_reduction" />
                    <el-option label="折扣活动" value="discount" />
                    <el-option label="买赠活动" value="buy_gift" />
                    <el-option label="秒杀活动" value="flash_sale" />
                    <el-option label="团购活动" value="group_buy" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    v-model="promotionForm.startTime"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker
                    v-model="promotionForm.endTime"
                    type="datetime"
                    placeholder="请选择结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="活动描述">
              <el-input v-model="promotionForm.description" type="textarea" :rows="3" placeholder="请输入活动描述" />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="规则配置" name="rules">
            <div v-if="promotionForm.type === 'full_reduction'">
              <h4>满减规则</h4>
              <el-form-item label="满足金额" prop="minAmount">
                <el-input-number v-model="promotionForm.minAmount" :min="0" :precision="2" style="width: 200px" />
                <span style="margin-left: 10px;">元</span>
              </el-form-item>
              <el-form-item label="减免金额" prop="discountAmount">
                <el-input-number v-model="promotionForm.discountAmount" :min="0" :precision="2" style="width: 200px" />
                <span style="margin-left: 10px;">元</span>
              </el-form-item>
            </div>
            
            <div v-if="promotionForm.type === 'discount'">
              <h4>折扣规则</h4>
              <el-form-item label="折扣方式" prop="discountType">
                <el-radio-group v-model="promotionForm.discountType">
                  <el-radio label="percentage">按折扣</el-radio>
                  <el-radio label="fixed">固定金额</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="折扣值" prop="discountValue">
                <el-input-number v-model="promotionForm.discountValue" :min="0" :precision="2" style="width: 200px" />
                <span style="margin-left: 10px;">{{ promotionForm.discountType === 'percentage' ? '折' : '元' }}</span>
              </el-form-item>
            </div>
            
            <div v-if="promotionForm.type === 'buy_gift'">
              <h4>买赠规则</h4>
              <el-form-item label="购买数量" prop="buyQuantity">
                <el-input-number v-model="promotionForm.buyQuantity" :min="1" style="width: 200px" />
                <span style="margin-left: 10px;">件</span>
              </el-form-item>
              <el-form-item label="赠送数量" prop="giftQuantity">
                <el-input-number v-model="promotionForm.giftQuantity" :min="1" style="width: 200px" />
                <span style="margin-left: 10px;">件</span>
              </el-form-item>
            </div>
            
            <el-form-item label="使用限制">
              <el-checkbox-group v-model="promotionForm.limitations">
                <el-checkbox label="limit_per_user">每人限用一次</el-checkbox>
                <el-checkbox label="member_only">仅限会员</el-checkbox>
                <el-checkbox label="new_user_only">仅限新用户</el-checkbox>
                <el-checkbox label="min_purchase">最低消费限制</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="适用商品" name="products">
            <el-form-item label="适用范围">
              <el-radio-group v-model="promotionForm.productScope">
                <el-radio label="all">全部商品</el-radio>
                <el-radio label="category">指定分类</el-radio>
                <el-radio label="specific">指定商品</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <div v-if="promotionForm.productScope === 'category'">
              <el-form-item label="商品分类">
                <el-select v-model="promotionForm.categories" multiple placeholder="请选择商品分类" style="width: 100%">
                  <el-option label="电子产品" value="electronics" />
                  <el-option label="服装鞋帽" value="clothing" />
                  <el-option label="家居用品" value="home" />
                  <el-option label="食品饮料" value="food" />
                  <el-option label="美妆护肤" value="beauty" />
                </el-select>
              </el-form-item>
            </div>
            
            <div v-if="promotionForm.productScope === 'specific'">
              <el-form-item label="指定商品">
                <el-button type="primary" @click="handleSelectProducts">选择商品</el-button>
                <div v-if="promotionForm.selectedProducts.length > 0" class="selected-products">
                  <el-tag
                    v-for="product in promotionForm.selectedProducts"
                    :key="product.id"
                    closable
                    @close="handleRemoveProduct(product)"
                    style="margin: 5px;"
                  >
                    {{ product.name }}
                  </el-tag>
                </div>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, VideoPlay, VideoPause, ArrowDown, Promotion, CircleCheck, Money, TrendCharts } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const isEdit = ref(false)
const currentPromotion = ref(null)
const selectedPromotions = ref([])
const activeTab = ref('basic')
const formActiveTab = ref('basic')
const promotionFormRef = ref(null)
const participationChart = ref(null)
const discountChart = ref(null)

// 促销统计数据
const promotionStats = reactive({
  totalPromotions: 45,
  activePromotions: 12,
  totalSavings: 158600,
  participationRate: 68.5
})

// 搜索表单
const searchForm = reactive({
  promotionName: '',
  type: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 促销活动表单
const promotionForm = reactive({
  promotionName: '',
  type: '',
  startTime: '',
  endTime: '',
  description: '',
  minAmount: 0,
  discountAmount: 0,
  discountType: 'percentage',
  discountValue: 0,
  buyQuantity: 1,
  giftQuantity: 1,
  limitations: [],
  productScope: 'all',
  categories: [],
  selectedProducts: []
})

// 表单验证规则
const promotionRules = {
  promotionName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    promotionNo: 'PM202401001',
    promotionName: '新年大促销',
    type: 'full_reduction',
    startTime: '2024-01-01 00:00:00',
    endTime: '2024-01-31 23:59:59',
    participantCount: 1580,
    totalSavings: 45600.00,
    status: 'active',
    createTime: '2023-12-20 10:30:00',
    creator: '张三',
    description: '新年期间全场满减活动，满500减100',
    rules: {
      condition: '单笔订单满500元',
      benefit: '立减100元',
      limitation: '每人限用3次，不与其他优惠同享'
    },
    applicableProducts: [
      { productCode: 'P001', productName: 'iPhone 15', category: '电子产品', price: 5999.00 },
      { productCode: 'P002', productName: 'MacBook Pro', category: '电子产品', price: 12999.00 }
    ],
    participants: [
      { memberNo: 'M001', memberName: '李四', orderNo: 'RT202401010001', originalAmount: 599.00, discountAmount: 100.00, finalAmount: 499.00, participateTime: '2024-01-15 14:30:00' },
      { memberNo: 'M002', memberName: '王五', orderNo: 'RT202401010002', originalAmount: 1299.00, discountAmount: 100.00, finalAmount: 1199.00, participateTime: '2024-01-15 16:45:00' }
    ]
  },
  {
    id: 2,
    promotionNo: 'PM202401002',
    promotionName: '会员专享8折',
    type: 'discount',
    startTime: '2024-01-10 00:00:00',
    endTime: '2024-02-10 23:59:59',
    participantCount: 890,
    totalSavings: 28900.00,
    status: 'active',
    createTime: '2024-01-05 09:15:00',
    creator: '李四',
    description: '会员专享折扣活动，全场8折优惠',
    rules: {
      condition: '会员身份验证',
      benefit: '全场商品8折',
      limitation: '仅限会员使用，每日限用1次'
    },
    applicableProducts: [
      { productCode: 'P003', productName: '智能手表', category: '电子产品', price: 2999.00 },
      { productCode: 'P004', productName: '蓝牙耳机', category: '电子产品', price: 599.00 }
    ],
    participants: [
      { memberNo: 'M003', memberName: '赵六', orderNo: 'RT202401100003', originalAmount: 2999.00, discountAmount: 599.80, finalAmount: 2399.20, participateTime: '2024-01-12 11:20:00' }
    ]
  },
  {
    id: 3,
    promotionNo: 'PM202401003',
    promotionName: '买二送一活动',
    type: 'buy_gift',
    startTime: '2024-01-15 00:00:00',
    endTime: '2024-01-25 23:59:59',
    participantCount: 456,
    totalSavings: 15680.00,
    status: 'active',
    createTime: '2024-01-08 14:20:00',
    creator: '王五',
    description: '指定商品买二送一，数量有限',
    rules: {
      condition: '购买指定商品2件',
      benefit: '赠送同款商品1件',
      limitation: '每人限参与1次，赠品不可退换'
    },
    applicableProducts: [
      { productCode: 'P005', productName: '保温杯', category: '家居用品', price: 199.00 },
      { productCode: 'P006', productName: '数据线', category: '电子产品', price: 59.00 }
    ],
    participants: [
      { memberNo: 'M004', memberName: '孙七', orderNo: 'RT202401150004', originalAmount: 398.00, discountAmount: 199.00, finalAmount: 398.00, participateTime: '2024-01-16 09:30:00' }
    ]
  },
  {
    id: 4,
    promotionNo: 'PM202401004',
    promotionName: '限时秒杀',
    type: 'flash_sale',
    startTime: '2024-01-20 10:00:00',
    endTime: '2024-01-20 12:00:00',
    participantCount: 2580,
    totalSavings: 68900.00,
    status: 'ended',
    createTime: '2024-01-18 16:45:00',
    creator: '赵六',
    description: '限时2小时秒杀活动，数量有限先到先得',
    rules: {
      condition: '活动时间内抢购',
      benefit: '秒杀价格购买',
      limitation: '每人限购1件，售完即止'
    },
    applicableProducts: [
      { productCode: 'P007', productName: '智能音箱', category: '电子产品', price: 299.00 }
    ],
    participants: [
      { memberNo: 'M005', memberName: '周八', orderNo: 'RT202401200005', originalAmount: 299.00, discountAmount: 100.00, finalAmount: 199.00, participateTime: '2024-01-20 10:05:00' }
    ]
  },
  {
    id: 5,
    promotionNo: 'PM202401005',
    promotionName: '团购优惠',
    type: 'group_buy',
    startTime: '2024-02-01 00:00:00',
    endTime: '2024-02-29 23:59:59',
    participantCount: 0,
    totalSavings: 0.00,
    status: 'pending',
    createTime: '2024-01-25 11:30:00',
    creator: '孙七',
    description: '团购活动，满10人成团享受优惠价格',
    rules: {
      condition: '满10人成团',
      benefit: '团购价格优惠',
      limitation: '成团后24小时内完成支付'
    },
    applicableProducts: [
      { productCode: 'P008', productName: '空气净化器', category: '家电', price: 1999.00 }
    ],
    participants: []
  }
]

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    full_reduction: 'danger',
    discount: 'warning',
    buy_gift: 'success',
    flash_sale: 'info',
    group_buy: 'primary'
  }
  return typeMap[type] || ''
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    full_reduction: '满减活动',
    discount: '折扣活动',
    buy_gift: '买赠活动',
    flash_sale: '秒杀活动',
    group_buy: '团购活动'
  }
  return typeMap[type] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    pending: 'info',
    active: 'success',
    ended: 'warning',
    paused: 'danger',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待开始',
    active: '进行中',
    ended: '已结束',
    paused: '已暂停',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 格式化优惠信息
const formatDiscountInfo = (row) => {
  switch (row.type) {
    case 'full_reduction':
      return '满500减100'
    case 'discount':
      return '全场8折'
    case 'buy_gift':
      return '买2送1'
    case 'flash_sale':
      return '秒杀价199元'
    case 'group_buy':
      return '团购价1599元'
    default:
      return '暂无信息'
  }
}

// 搜索
const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    loadData()
    loading.value = false
  }, 500)
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    promotionName: '',
    type: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 新建活动
const handleAdd = () => {
  isEdit.value = false
  Object.assign(promotionForm, {
    promotionName: '',
    type: '',
    startTime: '',
    endTime: '',
    description: '',
    minAmount: 0,
    discountAmount: 0,
    discountType: 'percentage',
    discountValue: 0,
    buyQuantity: 1,
    giftQuantity: 1,
    limitations: [],
    productScope: 'all',
    categories: [],
    selectedProducts: []
  })
  formActiveTab.value = 'basic'
  formDialogVisible.value = true
}

// 编辑活动
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(promotionForm, {
    id: row.id,
    promotionName: row.promotionName,
    type: row.type,
    startTime: row.startTime,
    endTime: row.endTime,
    description: row.description,
    minAmount: 500,
    discountAmount: 100,
    discountType: 'percentage',
    discountValue: 8,
    buyQuantity: 2,
    giftQuantity: 1,
    limitations: ['limit_per_user'],
    productScope: 'all',
    categories: [],
    selectedProducts: []
  })
  formActiveTab.value = 'basic'
  formDialogVisible.value = true
}

// 查看活动详情
const handleView = (row) => {
  currentPromotion.value = row
  activeTab.value = 'basic'
  detailDialogVisible.value = true
  
  // 延迟渲染图表
  nextTick(() => {
    if (activeTab.value === 'statistics') {
      renderCharts()
    }
  })
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialogVisible.value = false
  currentPromotion.value = null
}

// 下拉菜单命令处理
const handleDropdownCommand = async (command, row) => {
  switch (command) {
    case 'start':
      await handleStartPromotion(row)
      break
    case 'pause':
      await handlePausePromotion(row)
      break
    case 'resume':
      await handleResumePromotion(row)
      break
    case 'end':
      await handleEndPromotion(row)
      break
    case 'copy':
      await handleCopyPromotion(row)
      break
    case 'delete':
      await handleDeletePromotion(row)
      break
  }
}

// 启动活动
const handleStartPromotion = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要启动活动 ${row.promotionName} 吗？`, '确认启动', {
      type: 'info'
    })
    ElMessage.success('活动启动成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 暂停活动
const handlePausePromotion = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要暂停活动 ${row.promotionName} 吗？`, '确认暂停', {
      type: 'warning'
    })
    ElMessage.success('活动已暂停')
    loadData()
  } catch {
    // 用户取消
  }
}

// 恢复活动
const handleResumePromotion = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要恢复活动 ${row.promotionName} 吗？`, '确认恢复', {
      type: 'info'
    })
    ElMessage.success('活动已恢复')
    loadData()
  } catch {
    // 用户取消
  }
}

// 结束活动
const handleEndPromotion = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要结束活动 ${row.promotionName} 吗？结束后无法恢复`, '确认结束', {
      type: 'warning'
    })
    ElMessage.success('活动已结束')
    loadData()
  } catch {
    // 用户取消
  }
}

// 复制活动
const handleCopyPromotion = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要复制活动 ${row.promotionName} 吗？`, '确认复制', {
      type: 'info'
    })
    ElMessage.success('活动复制成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 删除活动
const handleDeletePromotion = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除活动 ${row.promotionName} 吗？此操作不可恢复`, '确认删除', {
      type: 'error'
    })
    ElMessage.success('活动删除成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 批量启动
const handleBatchStart = () => {
  if (selectedPromotions.value.length === 0) {
    ElMessage.warning('请选择要启动的活动')
    return
  }
  ElMessage.success('批量启动功能开发中...')
}

// 批量暂停
const handleBatchPause = () => {
  if (selectedPromotions.value.length === 0) {
    ElMessage.warning('请选择要暂停的活动')
    return
  }
  ElMessage.success('批量暂停功能开发中...')
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

// 选择商品
const handleSelectProducts = () => {
  ElMessage.success('商品选择功能开发中...')
}

// 移除商品
const handleRemoveProduct = (product) => {
  const index = promotionForm.selectedProducts.findIndex(p => p.id === product.id)
  if (index > -1) {
    promotionForm.selectedProducts.splice(index, 1)
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedPromotions.value = selection
}

// 提交表单
const handleSubmit = async () => {
  try {
    await promotionFormRef.value.validate()
    ElMessage.success(isEdit.value ? '活动更新成功' : '活动创建成功')
    formDialogVisible.value = false
    loadData()
  } catch {
    // 验证失败
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 渲染图表
const renderCharts = () => {
  if (participationChart.value) {
    const chart1 = echarts.init(participationChart.value)
    chart1.setOption({
      title: { text: '参与趋势', left: 'center' },
      xAxis: { type: 'category', data: ['1月1日', '1月2日', '1月3日', '1月4日', '1月5日'] },
      yAxis: { type: 'value' },
      series: [{
        data: [120, 200, 150, 80, 70],
        type: 'line',
        smooth: true
      }]
    })
  }
  
  if (discountChart.value) {
    const chart2 = echarts.init(discountChart.value)
    chart2.setOption({
      title: { text: '优惠分布', left: 'center' },
      series: [{
        type: 'pie',
        data: [
          { value: 1048, name: '满减优惠' },
          { value: 735, name: '折扣优惠' },
          { value: 580, name: '买赠优惠' },
          { value: 484, name: '秒杀优惠' }
        ]
      }]
    })
  }
}

// 监听tab切换
const handleTabChange = (tabName) => {
  if (tabName === 'statistics') {
    nextTick(() => {
      renderCharts()
    })
  }
}

// 加载数据
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 300)
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.promotion-management-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stats-icon {
  margin-right: 15px;
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.discount-info {
  display: flex;
  align-items: center;
}

.discount-text {
  color: #E6A23C;
  font-weight: 600;
}

.participant-count {
  color: #409EFF;
  font-weight: 600;
}

.savings-amount {
  color: #f56c6c;
  font-weight: 600;
}

.discount-amount {
  color: #67C23A;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.promotion-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.rules-config h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.statistics-content {
  padding: 20px 0;
}

.chart-container {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.chart-container h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  text-align: center;
}

.selected-products {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .promotion-management-container {
    padding: 10px;
  }
  
  .stats-row {
    flex-direction: column;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>